package com.campus.common.utils;


import com.campus.common.enums.VerifyCodeEnum;
import com.campus.common.exception.VerifyCodeException;
import com.campus.common.exception.VerifyCodeExceptionCode;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
public class VerifyCodeUtil {
    @Value("${spring.mail.username}")
    private String fromUsername;
    @Resource
    private JavaMailSender sender;
    @Resource
    private RedisCache redisCache;

    public void sendVerifyCode(String email, String verifyCodeEnum) {
        // 如果验证码仍生效， 不发送。
        if(redisCache.getCacheObject(verifyCodeEnum + email) != null) {
            throw new VerifyCodeException(VerifyCodeExceptionCode.SEND_CODE_REPEAT_ERROR);
        }
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromUsername);
        message.setTo(email);
        message.setSubject("你收到的的验证码为: ");
        Random random = new Random();
        Integer code = random.nextInt(899999) + 100000;
        message.setText("你收到的验证码为" + code + "，三分钟后失效，请及时注册！");
        sender.send(message);
        redisCache.setCacheObject(verifyCodeEnum + email ,code, 3, TimeUnit.MINUTES);
    }
}
